#!/usr/bin/env python
# encoding: utf-8
"""
ThingsProject.py

Created by Christopher Glasman on 2009-04-01.
Copyright (c) 2009 Christopher Glasman. 

This file is part of thingsplot.

thingsplot is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

thingsplot is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with thingsplot.  If not, see <http://www.gnu.org/licenses/>.

"""

# import sys
# import os
import time
# from matplotlib import dates
from numpy import zeros
from ThingsItem import ThingsItem
import ThingsDates as dates


class ThingsProject(object):
    """docstring for ThingsProject"""
    def __init__(self, title, ID, children, status, raw_date_created, raw_date_modified, raw_date_completed=None):
        super(ThingsProject, self).__init__()
        self.title = title
        self.ID = ID
        self.children = children
        self.item_list = [None]*len(self.children)
        self.item_list_objects = [None]*len(self.children)
        self.item_counter = 0
        self.item_object_counter = 0
        self.date_created = float(raw_date_created)
        if(raw_date_completed):
            self.date_completed = float(raw_date_completed)
        if(raw_date_modified):
            self.date_modified = float(raw_date_modified)
        self.status = status
        return
    
    def _print_(self):
        print "=============================================================================="
        print "Title: ", self.title
        print "------------------------------------------------------------------------------"
        print "ID: ", self.ID
        print "Contains ", len(self.children), " children: ", self.children
        self.list_items()
        print "------------------------------------------------------------------------------\n"
        return
    
    def add_item(self, ID, title, date_created, date_completed=None):
        self.item_list[self.item_counter] = [ID, title, date_created, date_completed]
        self.item_counter += 1
        return
    
    def add_item_object(self, title, ID, status, date_created, date_modified, date_completed=None):
        self.item_list_objects[self.item_object_counter] = ThingsItem(title, ID, status, date_created, date_modified, date_completed)
        self.item_object_counter += 1
        return
    
    def list_items(self, index=None):
        if(index):
            print self.item_list[index]
        else:
            for item in self.item_list:
                if(item): self.pretty_print(item)
            #
        #
        return
    
    def pretty_print(self, item):
        print "[", item[0], item[1], " > ", self.real_date(item[2]), " < ", self.real_date(item[3]), "]"
        return
    
    def real_date(self, date_str):
        try:
            df = float(date_str)
        except ValueError:
            return ""
        #boost to unix epoch from cocoa epoch
        df = df + (31.0*365.0 + 8)*24*60*60 #there are 8 leap years between 1970 and 2001
        d = time.ctime(df)
        return d
    
    
    def get_dates_created(self):
        days = [None]*len(self.children)
        for i in range(len(self.children)):
            raw_t = self.item_list[i][2]
            # days[i] = float(raw_t)/24.0/60.0/60.0 + 2000.0*(365 + 0.25)
            days[i] = dates.epoch2num(float(raw_t) + 31*365*24*60*60 ) #Now UTC days?
        return days
    
    
    def order_items_by_creation(self):
        times_created = [None]*len(self.children)
        for i in range(len(self.children)):
            raw_t = self.item_list_objects[i].date_created
            times_created[i] = raw_t
        ordered_item_list_objects = [None]*len(self.children)
        i=0
        for time in sorted(times_created):
            for todo in self.item_list_objects:
                if(time == todo.date_created):
                    ordered_item_list_objects[i] = todo
            i += 1 
        # now replace the unsorted list with the sorted one
        self.item_list_objects = ordered_item_list_objects
        # for todo in self.item_list_objects:
        #     print self.real_date(todo.date_created), todo.title
        return
    
    def get_dates_completed(self):
        # days = [None]*len(self.children)
        days = [ ] # making this change for slower "append" approach since not all completed. 
        for i in range(len(self.children)):
            raw_t = self.item_list[i][3]
            if(raw_t != ""):
                # days[i] = float(raw_t)/24.0/60.0/60.0 + 2001.0*365
                # days[i] = dates.epoch2num(float(raw_t) + 31*365*24*60*60 )
                days.append(dates.epoch2num(float(raw_t) + 31*365*24*60*60 ) )
                
        return days
    
    
    def get_outstanding_items(self):
        debug=0
        self.tic()
        times_created=[]
        times_completed=[]
        # times_created = array(self.item_list[:][2])
        q=0
        for i in range(len(self.children)):
            raw_t = self.item_list[i][2] #created time
            raw_t_comp = self.item_list[i][3]
            times_created.append(float(raw_t))
            if(raw_t_comp != ""): 
                times_completed.append(float(raw_t_comp))
            else:
                # print q, " not completed: ", self.item_list[i][0], self.item_list[i][1]
                q += 1
        # times_created = sort(array(times_created)*1.0 )
        times_created.sort()
        # times_completed = sort(array(times_completed)*1.0 )
        times_completed.sort()
        #now loop through time created list - compare with first completed time until
        # find created after completed. Then insert completed time. 
        num_outstanding=0
        days = zeros( (len(times_created) + len(times_completed) )  )
        # outstanding = days
        outstanding = zeros(len(days) )
        completed_counter = 0
        created_counter = 0
        if(debug==1):
            print "days", days
            print "outstanding", outstanding
            print "times_created: ", times_created
            print "times_completed: ", times_completed
        for j in range(len(days)):
            if(debug==1):
                print "created_counter: ", created_counter
            if(created_counter < len(times_created)):
                t_created = times_created[created_counter]
            if(completed_counter < len(times_completed)):
                t_completed = times_completed[completed_counter]
            # print "j ", j, " tcreated: ", t_created, " tcompleted: ", t_completed
            if(t_created <= t_completed and created_counter < len(times_created) ):
                # print "created"
                created_counter += 1
                #dates.epoch2num(float(raw_t) + 31*365*24*60*60 )
                # days[j] = t_created
                days[j] = dates.epoch2num(t_created + 31*365*24*60*60 )
                # days[j-1] = days[j]
                # outstanding[j] = created_counter - completed_counter
            elif(completed_counter > len(times_completed)):
                print "Items created after the last completed item. "
                created_counter += 1
                days[j] = dates.epoch2num(t_created + 31*365*24*60*60 )
            else:
                # print "completed"
                completed_counter += 1
                days[j] = dates.epoch2num(t_completed + 31*365*24*60*60 )
                # days[j-1] = days[j]
                # days[j] = t_completed
                # outsanding[j] = created_counter - completed_counter
            outstanding[j] = created_counter - completed_counter
            # print "j ", j, outstanding[j], created_counter, completed_counter
            # outstanding[j-1] = outstanding[j-2]
            # print "j, time, outstanding: ", j
        # print days
        # print outstanding
        t = self.toc()
        print "outstanding item loop took: ", t, " seconds. "
        return days, outstanding


    def tic(self):
        # print "started...."
        self.start = time.time()
        return

    def toc(self):
        duration = time.time() - self.start
        return duration

#







